/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * PmTaskController
 * 任务管理
 * <p>
 * 修改纪录
 * 2020-05-14 版本：1.0 wushenghong 创建。
 *
 * @version 版本：1.0
 * @author 作者：wushenghong
 * 创建日期：2020-05-14
 */

package com.topscomm.pm.controller;

import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.pm.controller.auto.PmTaskControllerAuto;
import com.topscomm.pm.pojo.PmProjectEntity;
import com.topscomm.pm.service.impl.PmProjectService;
import com.topscomm.pm.utils.MisStringUtil;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.common.TapSystemConst;
import java.util.HashMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: wushenghong
 * @date: 2020-05-14
 * @description:任务管理Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/task")
public class PmTaskController extends PmTaskControllerAuto implements IPmTaskController {

    @Resource
    private PmProjectService pmProjectService;

    /**
     * @param paraMap
     * @return
     * @author: wushenghong
     * @date: 2020-05-14
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" PmTask.enabled=1 ");
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and projectid={0}", value);
        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and state={0}", value);
        }
        if (paraMap.containsKey("qry_taskstate")) {
            String value = paraMap.get("qry_taskstate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and taskstate={0}", value);
        }
        if (paraMap.containsKey("qry_leadername")) {
            String value = paraMap.get("qry_leadername").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and leadername like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_docno")) {
            String value = paraMap.get("qry_docno").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and docno like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        sql .appendSingle(this.spellingSqlForProject(paraMap, "PmTask","projectid","id"));
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        if (paraMap.containsKey("qry_username")) {
            String value = paraMap.get("qry_username").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and username like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_user")) {
            String value = paraMap.get("qry_user").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and ( leadername like '%{0}%' or participantnames like '%{0}%' )", value);
        }
        if (paraMap.containsKey("qry_deptcode")) {
            String value = paraMap.get("qry_deptcode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and deptcode like '{0}%'", value);
        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and state={0}", value);
        }
        if (paraMap.containsKey("qry_taskcategory")) {
            String value = paraMap.get("qry_taskcategory").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and taskcategory = '{0}'", value);
        }
        if (paraMap.containsKey("qry_where")) {
            String value = paraMap.get("qry_where").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and {0}", value);
        }
        if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
        {
            String dataPession = service.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "", this.getUserBean());
            if (StringUtil.isEmpty(dataPession)) {
//                sql.appendSingle(MisStringUtil.createWhereByUsercodeFromProject(this.getUserBean().getUser().getCode(), "projectid", service.getDao().getTableName()));
                sql.appendSingle(" and (" + MisStringUtil.createWhereByUsercodeFromProject(
                        this.getUserBean().getUser(), "projectid",
                        service.getDao().getTableName()) + " or PmTask.participantcodes like '%{0}%' or  PmTask.leadercode = '{0}')", this.getUserBean().getUser().getCode());
            } else// 使用数据权限
            {
                StringBufferProxy sqltemp = new StringBufferProxy();
                sqltemp.appendSingle("  (" + MisStringUtil.createWhereByUsercodeFromProject(
                        this.getUserBean().getUser(), "projectid",
                        service.getDao().getTableName()) + " or PmTask.participantcodes like '%{0}%' or  PmTask.leadercode = '{0}'", this.getUserBean().getUser().getCode());
                sql.appendSingle(" and (({0}) or ({1})  ) ", dataPession,sqltemp.toString());
            }
        }
        return sql.toString();
    }

    //=========================任务查询相关====================================================================================================

    protected String spellListSqlStatistics(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" PmTask.enabled=1 ");
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and projectid={0}", value);
        }
        if (paraMap.containsKey("qry_relatedName")) {
            String value = paraMap.get("qry_relatedName").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (leadername like '%{0}%' or participantnames like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_relatedCode")) {
            String value = paraMap.get("qry_relatedCode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (leadercode = '{0}' or participantcodes like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        if (paraMap.containsKey("qry_taskstate")) {
            String value = paraMap.get("qry_taskstate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and taskstate={0}", value);
        }
        if (paraMap.containsKey("qry_taskcategory")) {
            String value = paraMap.get("qry_taskcategory").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and taskcategory = '{0}'", value);
        }
        return sql.toString();
    }

    @GetMapping({"/listStatistics"})
    public ResponseResult<Object> listStatistics(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSqlStatistics(paraMap);
            int totalCount = ((ITapService)this.service).getCount(sqlWhere);
            List<Map<String, Object>> tempList = null;
            if (query.getPageSize() > 0) {
                tempList = ((ITapService)this.service).queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
            } else {
                tempList = ((ITapService)this.service).queryMapByWhere(sqlWhere);
            }

            ((ITapService)this.service).setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }

    //=========================任务查询相关结束====================================================================================================

    /**
     * @param paraMap
     * @return
     * @author: wushenghong
     * @date: 2020-05-14
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }

    /**
     * @param dataMap
     * @param paraMap
     * @throws Exception
     * @description: 提交审批前
     * @author: wushenghong
     * @date: 2020-05-14
     * @modify:
     */
    @Override
    protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
        super.beforeSubmit(dataMap, paraMap);
        StringBufferProxy mailtitle = new StringBufferProxy();
        mailtitle.appendSingle("{0}{1}于{2}提交任务管理申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
        dataMap.put("maintitle", mailtitle.toString());
        List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmTask", dataMap.get("deptcode").toString(),dataMap.get("usercode").toString(),null, "sortcode");
        Long flowid = flowidList.size()>0? ConvertUtil.convertToLong(flowidList.get(0).get("id")) :null;
        dataMap.put("flowid", flowid);
    }

    // 取消任务
    @PutMapping(value = "/cancelTask")
    public ResponseResult<Object> cancelTask(@RequestBody(required = false) Map<String, Object> paraMap) {
        if (this.service.executeCancelTask(paraMap)) {
            return ResponseResult.ok("任务取消成功！");
        } else {
            return ResponseResult.error("任务取消失败，请联系系统管理员处理！");
        }
    }

    // 查询项目信息
    @GetMapping(value = "/queryProjectById")
    public ResponseResult<Object> queryProjectById(@RequestParam(required = false) Map<String, Object> paraMap) {
        String projectId = paraMap.get("projectId").toString();
        PmProjectEntity pmProjectEntity = pmProjectService.queryById(projectId);
        return ResponseResult.ok(pmProjectEntity);
    }

    @Override
    protected void afterLoad(Map<String, Object> paraMap) {
        super.afterLoad(paraMap);
        String projectId = ConvertUtil.convertToString(paraMap.get("projectid"));
        PmProjectEntity pmProjectEntity = pmProjectService.queryById(projectId);
        paraMap.put("projectcode", pmProjectEntity.getCode());
        paraMap.put("planstarttime", pmProjectEntity.getPlanstarttime());
        paraMap.put("planendtime", pmProjectEntity.getPlanendtime());
    }
    /**
     * 批量补录工作日志
     * @param paraMap
     * @return
     */
//    @PutMapping(value = "/supplementTaskLog")
//    public ResponseResult<Object> supplementTaskLog(@RequestBody(required = false) Map<String, Object> paraMap) {
//        this.service.supplementTaskLog(paraMap);
//        return ResponseResult.ok("工作日志补录成功！");
//    }

    @Override
    @GetMapping({"/list"})
    public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSql(paraMap);
            paraMap.put("whereSql",sqlWhere);
            int totalCount = this.service.getCount(paraMap,"getPmTaskAndProjectCount");
            List<Map<String, Object>> tempList = null;
            HashMap<String, Object> paraMap2 = new HashMap<>();
            paraMap2.put("curPageIndex",query.getCurrentPage());
            int beginCount=query.getCurrentPage()*query.getPageSize()-query.getPageSize();
            paraMap2.put("begincount",beginCount);
            paraMap2.put("pagesize", query.getPageSize());
            paraMap2.put("sidx", query.getSidx());
            paraMap2.put("sord", query.getSord());
            paraMap2.put("whereSql", sqlWhere);
            if (query.getPageSize() > 0) {
                tempList = this.service.queryMapForPage(paraMap2,"getPmTaskAndProject");
            } else {
                tempList = this.service.queryMap(paraMap2,"queryMapByWhere1");
            }
            this.service.setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }
}

